<template>
  <div class="reviews-reports-container">
    <h1>评论管理</h1>

    <!-- 筛选和搜索工具栏 -->
    <div class="toolbar">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-select v-model="filterRating" placeholder="评分筛选" clearable>
            <el-option label="全部" value="" />
            <el-option label="5星" :value="5" />
            <el-option label="4星" :value="4" />
            <el-option label="3星" :value="3" />
            <el-option label="2星" :value="2" />
            <el-option label="1星" :value="1" />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-col>
        <el-col :span="6">
          <el-select v-model="filterStatus" placeholder="状态筛选" clearable>
            <el-option label="全部" value="" />
            <el-option label="已回复" value="已回复" />
            <el-option label="未回复" value="未回复" />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-input v-model="searchKeyword" placeholder="搜索关键词" clearable>
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-col>
      </el-row>
    </div>

    <!-- 评论列表 -->
    <el-table
      v-loading="loading"
      :data="filteredReviews"
      style="width: 100%; margin-top: 20px"
      @row-click="handleRowClick"
    >
      <el-table-column prop="facilityName" label="设施名称" min-width="120" />
      <el-table-column prop="date" label="评论日期" width="100" sortable />
      <el-table-column prop="username" label="用户名" width="100" />
      <el-table-column label="评分" width="120">
        <template #default="scope">
          <el-rate
            v-model="scope.row.rating"
            disabled
            show-score
            text-color="#ff9900"
          />
        </template>
      </el-table-column>
      <el-table-column prop="comment" label="评论内容" min-width="200" show-overflow-tooltip />
      <el-table-column label="状态" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.adminReply ? 'success' : 'info'">
            {{ scope.row.adminReply ? '已回复' : '未回复' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150" fixed="right">
        <template #default="scope">
          <el-button
            size="small"
            type="primary"
            @click.stop="handleEdit(scope.row)"
          >
            {{ scope.row.adminReply ? '查看' : '回复' }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页控件 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="filteredReviews.length"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 评论详情对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="评论详情"
      width="50%"
      destroy-on-close
    >
      <el-form
        v-if="currentReview"
        :model="currentReview"
        label-width="100px"
        :disabled="isSubmitting"
      >
        <el-form-item label="设施名称">
          <el-input v-model="currentReview!.facilityName" disabled />
        </el-form-item>
        <el-form-item label="评论日期">
          <el-input v-model="currentReview!.date" disabled />
        </el-form-item>
        <el-form-item label="用户名">
          <el-input v-model="currentReview!.username" disabled />
        </el-form-item>
        <el-form-item label="总体评分">
          <el-rate v-model="currentReview!.rating" disabled show-score />
        </el-form-item>
        <el-form-item label="清洁度">
          <el-rate v-model="currentReview!.cleanliness" disabled show-score />
        </el-form-item>
        <el-form-item label="设施">
          <el-rate v-model="currentReview!.facility" disabled show-score />
        </el-form-item>
        <el-form-item label="便利性">
          <el-rate v-model="currentReview!.convenience" disabled show-score />
        </el-form-item>
        <el-form-item label="评论内容">
          <el-input
            v-model="currentReview!.comment"
            type="textarea"
            :rows="4"
            disabled
          />
        </el-form-item>
        <el-form-item label="管理员回复">
          <el-input
            v-model="currentReview!.adminReply"
            type="textarea"
            :rows="4"
            placeholder="请输入回复内容"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSaveReview" :loading="isSubmitting">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import FeatureLayer from '@arcgis/core/layers/FeatureLayer'

// 定义评论记录接口
interface Review {
  id: string
  facilityId: string
  facilityName: string
  username: string
  rating: number
  comment: string
  date: string
  cleanliness: number
  facility: number
  convenience: number
  adminReply?: string
}

// 状态变量
const loading = ref(true)
const allReviews = ref<Review[]>([])
const filterRating = ref('')
const filterStatus = ref('')
const dateRange = ref([])
const searchKeyword = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const dialogVisible = ref(false)
const currentReview = ref<Review | null>(null)
const isSubmitting = ref(false)

// 筛选后的评论列表
const filteredReviews = computed(() => {
  let result = allReviews.value

  // 应用筛选条件
  if (filterRating.value) {
    result = result.filter(review => review.rating === Number(filterRating.value))
  }

  if (filterStatus.value) {
    if (filterStatus.value === '已回复') {
      result = result.filter(review => review.adminReply)
    } else if (filterStatus.value === '未回复') {
      result = result.filter(review => !review.adminReply)
    }
  }

  // 应用日期范围筛选
  if (dateRange.value && dateRange.value.length === 2) {
    const startDate = dateRange.value[0]
    const endDate = dateRange.value[1]
    result = result.filter(review => {
      // 将日期字符串转换为时间戳进行比较
      const reviewDate = new Date(review.date).getTime()
      const start = new Date(startDate).getTime()
      const end = new Date(endDate).getTime()
      return reviewDate >= start && reviewDate <= end
    })
  }

  // 应用搜索关键词
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    result = result.filter(review =>
      review.facilityName.toLowerCase().includes(keyword) ||
      review.comment.toLowerCase().includes(keyword) ||
      review.username.toLowerCase().includes(keyword)
    )
  }

  return result
})

// 分页相关方法
const handleSizeChange = (val: number) => {
  pageSize.value = val
  currentPage.value = 1
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
}

// 行点击事件
const handleRowClick = (row: Review) => {
  currentReview.value = JSON.parse(JSON.stringify(row)) // 深拷贝
  dialogVisible.value = true
}

// 编辑按钮点击事件
const handleEdit = (row: Review) => {
  currentReview.value = JSON.parse(JSON.stringify(row)) // 深拷贝
  dialogVisible.value = true
}

// 保存评论回复
const handleSaveReview = async () => {
  if (!currentReview.value) return

  isSubmitting.value = true
  try {
    // 创建卫生间设施要素图层
    const bathroomLayer = new FeatureLayer({
      url: 'https://services.arcgis.com/Jaqp8M1tVnnHQ5RM/arcgis/rest/services/Bathroom_FacilitiesManagementSystem/FeatureServer/0',
      outFields: ['*']
    })

    // 查询要素
    const query = {
      where: `OBJECTID = ${currentReview.value.facilityId}`,
      outFields: ['*'],
      returnGeometry: false
    }

    const featureSet = await bathroomLayer.queryFeatures(query)

    if (featureSet.features.length > 0) {
      const feature = featureSet.features[0]
      let reviews = []

      try {
        // 解析现有评论列表
        reviews = JSON.parse(feature.attributes.reviews || '[]')

        // 更新当前评论
        const index = reviews.findIndex((review: any) =>
          review.date === currentReview.value?.date &&
          review.username === currentReview.value?.username &&
          review.comment === currentReview.value?.comment
        )

        if (index !== -1) {
          reviews[index] = {
            ...reviews[index],
            adminReply: currentReview.value.adminReply
          }

          // 克隆要素并更新属性
          const updatedFeature = feature.clone()
          updatedFeature.attributes.reviews = JSON.stringify(reviews)

          // 应用编辑
          const results = await bathroomLayer.applyEdits({
            updateFeatures: [updatedFeature]
          })

          if (results.updateFeatureResults.length > 0) {
            ElMessage.success('评论回复已保存')
            dialogVisible.value = false

            // 更新本地列表
            const updatedReview = {
              ...currentReview.value,
              adminReply: currentReview.value.adminReply
            }

            const localIndex = allReviews.value.findIndex(review =>
              review.date === updatedReview.date &&
              review.username === updatedReview.username &&
              review.comment === updatedReview.comment
            )

            if (localIndex !== -1) {
              allReviews.value[localIndex] = updatedReview
            }
          } else {
            ElMessage.error('保存失败')
          }
        } else {
          ElMessage.error('未找到对应的评论记录')
        }
      } catch (error) {
        console.error('处理评论记录失败:', error)
        ElMessage.error('处理评论记录失败')
      }
    } else {
      ElMessage.error('未找到对应的设施')
    }
  } catch (error) {
    console.error('保存评论回复失败:', error)
    ElMessage.error('保存评论回复失败')
  } finally {
    isSubmitting.value = false
  }
}

// 加载所有评论记录
const loadAllReviews = async () => {
  loading.value = true
  try {
    // 创建卫生间设施要素图层
    const bathroomLayer = new FeatureLayer({
      url: 'https://services.arcgis.com/Jaqp8M1tVnnHQ5RM/arcgis/rest/services/Bathroom_FacilitiesManagementSystem/FeatureServer/0',
      outFields: ['*']
    })

    // 查询所有设施
    const query = {
      where: '1=1', // 查询所有记录
      outFields: ['*'],
      returnGeometry: false
    }

    const featureSet = await bathroomLayer.queryFeatures(query)

    if (featureSet.features.length > 0) {
      const tempReviews: Review[] = []

      // 遍历所有设施，提取评论记录
      featureSet.features.forEach(feature => {
        try {
          if (feature.attributes.reviews) {
            const reviewsList = JSON.parse(feature.attributes.reviews || '[]')

            if (reviewsList.length > 0) {
              // 为每个评论添加设施信息
              const facilityReviews = reviewsList.map((review: any) => ({
                ...review,
                facilityId: feature.attributes.OBJECTID,
                facilityName: feature.attributes.name || '未知设施',
                id: `${feature.attributes.OBJECTID}-${review.date}-${Math.random().toString(36).substring(2, 10)}`
              }))

              tempReviews.push(...facilityReviews)
            }
          }
        } catch (error) {
          console.error('解析设施评论记录失败:', error)
        }
      })

      // 按日期排序（最新的在前）
      allReviews.value = tempReviews.sort((a, b) => {
        return new Date(b.date).getTime() - new Date(a.date).getTime()
      })

      ElMessage.success(`成功加载 ${allReviews.value.length} 条评论记录`)
    } else {
      ElMessage.warning('未找到任何设施记录')
    }
  } catch (error) {
    console.error('加载评论记录失败:', error)
    ElMessage.error('加载评论记录失败')
  } finally {
    loading.value = false
  }
}

// 页面加载时获取所有评论记录
onMounted(() => {
  loadAllReviews()
})
</script>

<style scoped>
.reviews-reports-container {
  padding: 20px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.toolbar {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>